﻿using MgSoft.Excel.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace MgSoft.Excel.Model.Excel
{
    public class MgSheet : IMgSheet
    {
        public int StartRowIndex { get; private set; }

        /// <summary>
        /// maxRowIndex=-1表示没有数据
        /// </summary>
        public int MaxRowIndex { get; private set; } = -1;

        void IMgSheet.SetStartRowIndex(int startRowIndex)
        {
            this.StartRowIndex = startRowIndex;
        }

        void IMgSheet.SetMaxRowIndex(int maxRowIndex)
        {
            this.MaxRowIndex = maxRowIndex;
        }

        public List<MgCell> MgCells { get; private set; }

        public MgSheet()
        {
            MgCells = new List<MgCell>();
        }

        public MgRow GetRow(int rowIndex)
        {
            return new MgRow(MgCells.Where(p => p.RowIndex == rowIndex).ToList(), rowIndex);
        }

        public MgCell GetCell(int rowIndex, int columnIndex)
        {
            return MgCells.Where(p => p.RowIndex == rowIndex && p.ColumnIndex == columnIndex).FirstOrDefault();
        }
        public MgCell GetCell(int rowIndex, string columnName)
        {
            return GetCell(rowIndex, SheetColumnNameUtil.ColumnNameToColumnIndex(columnName));
        }

        //public MgCell Get(int rowIndex,string columnName)
        //{

        //}

        public void Add(MgCell mgCell)
        {
            //this.Remove(mgCell);
            MgCells.Add(mgCell);
        }

        public bool Remove(MgCell mgCell)
        {
            return this.Remove(mgCell.RowIndex, mgCell.ColumnIndex);
        }

        public bool Remove(int rowIndex, int columnIndex)
        {
            var existCell = this.GetCell(rowIndex, columnIndex);

            if (existCell != null)
            {
                this.MgCells.Remove(existCell);
                return true;
            }
            return false;
        }

        public bool IsHasRow()
        {
            return MaxRowIndex > 0;
        }

        public int GetTotleRow()
        {
            if (!IsHasRow()) return 0;

            return MaxRowIndex - StartRowIndex + 1;
        }
    }
}
